<?php

class AudiosController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','suggestTags','batUpload'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModelBySalt($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Audios('create');
		
		$mp3 = Yii::app() -> mp3file;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_FILES['Audios']) && isset($_POST['Audios']))
		{
			$model -> attributes = $_POST['Audios'];
			$upload = UploadedFile::getInstance ( $model, 'audio_file' );
			
			$uploadCover = UploadedFile::getInstance ( $model, 'audio_cover' );
			
			$model -> audio_file = $upload;
			$model -> audio_cover = $uploadCover;
			//$audio_file -> saveAs();
			#$model->attributes=$_POST['Audios'];
			if($model -> validate()){
				
				$mp3 -> setFile($upload -> getTempName());
				$metaData = $mp3 -> get_metadata();
				
				$length = $metaData['Length'];
				$model -> audio_length= $length;
				$model -> audio_size = $upload -> getSize();
				$model -> audio_from = Yii::app() -> user -> id;
				$model -> audio_name = $_POST['Audios']['audio_name'];
				$model -> audio_likes = 0;
				$model -> audio_status= 1;
				$model -> audio_playtimes = 0;
				$model -> audio_dateline = time();
				
				//音频保存
				$audioSavePath = $this -> _saveAudioFile($upload);
				$model -> audio_file  = $audioSavePath;
				
				//音频图片
				$coverSavePath = $this -> _saveAudioCover($uploadCover);
				$model -> audio_cover = $coverSavePath;
				
				//音频上传
				Yii::app() -> qiniu -> uploadAudio($audioSavePath,Yii::app ()->params->audioUploadPath.$audioSavePath);
				
				//音频图片保存的地址
				Yii::app() -> qiniu -> uploadImg($coverSavePath,Yii::app ()->params->imgUploadPath.$coverSavePath);
				
				if($model->save())
					$this->redirect(array('view','id'=>$model->audio_saltid));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	public function actionBatUpload(){
		
		$path = 'D:\wamp\www\mp3s\s';;
		
		$from_id = 10010;
		
		$files = scandir($path);
		foreach($files as $file){
			if(!in_array($file, array('.','..'))){
				
				$file_path = $path.DIRECTORY_SEPARATOR.$file;
				
				$model=new Audios('create');
				$mp3 = Yii::app() -> mp3file;
				
				#$uploadCover = UploadedFile::getInstance ( $model, 'audio_cover' );
					
				#$model -> audio_file = $upload;
				#$model -> audio_cover = $uploadCover;
				//$audio_file -> saveAs();
				#$model->attributes=$_POST['Audios'];
				$mp3 -> setFile($file_path);
				
				$metaData = $mp3 -> get_metadata();
				
				var_dump($metaData);
				die;
			
				$length = $metaData['Length'];
				$model -> audio_length= $length;
				$model -> audio_size = $upload -> getSize();
				$model -> audio_from = $from_id;
				$model -> audio_name = 'need be edit';
				$model -> audio_likes = 0;
				$model -> audio_status= 1;
				$model -> audio_playtimes = 0;
				$model -> audio_dateline = time();
			
				//音频保存
				$audioSavePath = $this -> _saveAudioFile($upload);
				$model -> audio_file  = $audioSavePath;
			
				//音频图片
				$coverSavePath = $this -> _saveAudioCover($uploadCover);
				$model -> audio_cover = $coverSavePath;
			
				//音频上传
				Yii::app() -> qiniu -> uploadAudio($audioSavePath,Yii::app ()->params->audioUploadPath.$audioSavePath);
			
				//音频图片保存的地址
				Yii::app() -> qiniu -> uploadImg($coverSavePath,Yii::app ()->params->imgUploadPath.$coverSavePath);
			}
		}
	}
	
	/**
	 * 
	 * @param UploadedFile $upload
	 * @return mixed
	 */
	private function _saveAudioFile($upload){
		$ext = $upload->getExtensionName ();
		$name = md5 ( $upload->getName () . time () );
		$name = $name . '.' . $ext;
		$path = Yii::app ()->getParams ();
		$UploadPath = $path->audioUploadPath;
		$folder = UploadedFile::getFolder ( $UploadPath );
		$upload->saveAs ( $folder . '/' . $name );
		$img_url = $folder . '/' . $name;
		return str_replace($UploadPath, '', $img_url);;
	}
	
	/**
	 * 
	 * @param UploadedFile $upload
	 */
	private function _saveAudioCover($upload){
		$ext = $upload->getExtensionName ();
		$name = md5 ( $upload->getName () . time () );
		$name = $name . '.' . $ext;
		$path = Yii::app ()->getParams ();
		$UploadPath = $path->imgUploadPath;
		$folder = UploadedFile::getFolder ( $UploadPath );
		$upload->saveAs ( $folder . '/' . $name );
		$img_url = $folder . '/' . $name;
		return str_replace($UploadPath, '', $img_url);;
	}
	
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Audios']))
		{
			$model->attributes=$_POST['Audios'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->audio_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Audios');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Audios('search');
		$model->unsetAttributes();  // clear any default values
		
		if(!Yii::app() -> user -> isAdmin()){
			$model -> audio_from = Yii::app() -> user -> id;
		}
		if(isset($_GET['Audios']))
			$model->attributes=$_GET['Audios'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Suggests tags based on the current user input.
	 * This is called via AJAX when the user is entering the tags input.
	 */
	public function actionSuggestTags()
	{
		if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
		{
			$tags=AudioTags::model()->suggestTags($keyword);
			if($tags!==array())
				echo implode("\n",$tags);
		}
	}
	
	/**
	 * 
	 * @param string $id
	 * @throws CHttpException
	 */
	public function loadModelBySalt($id){
		$model=Audios::model()->findByAttributes(array('audio_saltid'=>$id));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Audios::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='audios-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
